<template>
  <div>
    <div class="cover-image-box">
      <span>iAccount</span>
    </div>
    <div class="form-container">
      <Transition name="login" appear>
      <el-form
        ref="loginFormRef"
        :rules="rules_log"
        class="form-box"
        :model="loginForm"
        label-position="top"
        size="large"
        v-if="tabActive === 'login'"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" clearable @keyup.enter="logPwdIpt.focus()">
            <template #prefix>
              <svg class="icon" aria-hidden="true" style="color: black;"><use xlink:href="#icon-wode"></use></svg>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input ref="logPwdIpt" v-model="loginForm.password" type="password" show-password clearable @keyup.enter="doLogin">
            <template #prefix>
              <svg class="icon" aria-hidden="true"><use xlink:href="#icon-mima"></use></svg>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-checkbox v-model="loginForm.keepme" label="记住我" />
        </el-form-item>
        <el-form-item>
          <span class="switch-tag" @click="handleTabChange">没有账号？</span>
        </el-form-item>
        <el-form-item>
          <el-button class="affair-button" @click="doLogin" type="primary">登录</el-button>
        </el-form-item>
        <div class="version">{{ version }}</div>
      </el-form>
      </Transition>
      <Transition name="reg">
      <el-form
        ref="regFormRef"
        class="form-box"
        :rules="rules_reg"
        :model="regForm"
        label-position="top"
        size="large"
        v-if="tabActive !== 'login'"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="regForm.username" clearable @keyup.enter="regPwdIpt.focus()">
            <template #prefix>
              <svg class="icon" aria-hidden="true" style="color: black;"><use xlink:href="#icon-wode"></use></svg>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input ref="regPwdIpt" v-model="regForm.password" type="password" show-password clearable @keyup.enter="regRePwdIpt.focus()">
            <template #prefix>
              <svg class="icon" aria-hidden="true"><use xlink:href="#icon-mima"></use></svg>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password_re">
          <el-input ref="regRePwdIpt" v-model="regForm.password_re" type="password" show-password clearable @keyup.enter="doRegister">
            <template #prefix>
              <svg class="icon" aria-hidden="true"><use xlink:href="#icon-mima"></use></svg>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <span class="switch-tag" @click="handleTabChange">已有账号？</span>
        </el-form-item>
        <el-form-item>
          <el-button class="affair-button" @click="doRegister" type="primary">注册</el-button>
        </el-form-item>
        <div class="version">{{ version }}</div>
      </el-form>
      </Transition>
    </div>
  </div>
</template>

<script setup>
  import { useRouter } from 'vue-router';
  import { reactive, ref, onMounted } from 'vue';
  import { useUserStore } from '@/stores/user';
  import { loginReq, registerReq } from '@/utils/api';
  import message from '@/utils/message';

  const version = import.meta.env.VITE_VERSION;
  const router = useRouter();
  const useUser = useUserStore();
  const logPwdIpt = ref();
  const regPwdIpt = ref();
  const regRePwdIpt = ref();

  let tabActive = ref('login');
  function handleTabChange() {
    if(tabActive.value === 'login') {
      tabActive.value = 'register';
      Object.assign(loginForm, { username: "", password: "" });
    } else {
      tabActive.value = 'login';
      readRememberInfo();
    }
  }

  const loginFormRef = ref();
  let loginForm = reactive({
    username: "",
    password: "",
    keepme: false,
  });
  function doLogin() {
    loginFormRef.value.validate((valid) => {
      if(valid) {
        loginReq(loginForm.username, loginForm.password)
          .then(res => {
            if(res.data.msg === "成功") {
              const data = res.data.data;
              rememberMe();
              useUser.setUser(data.account, data.id);
              router.push('/home');
            } else {
              message.warning(res.data.msg);
            }
          })
          .catch(err => {
            message.warning('系统出错，请重试');
            console.warn(err);
          });
      }
    });
  }
  
  function rememberMe() {
    localStorage.removeItem('iaccount_keepme_bool_4a5bef');
    localStorage.removeItem('iaccount_username_7c66fa');
    localStorage.removeItem('iaccount_password_ac61be');
    if(loginForm.keepme) {
      localStorage.setItem('iaccount_keepme_bool_4a5bef', loginForm.keepme);
      localStorage.setItem('iaccount_username_7c66fa', loginForm.username);
      localStorage.setItem('iaccount_password_ac61be', loginForm.password);
    }
  }
  function readRememberInfo() {
    loginForm.keepme = localStorage.getItem('iaccount_keepme_bool_4a5bef') === 'true' ? true : false;
    loginForm.username = localStorage.getItem('iaccount_username_7c66fa') || '';
    loginForm.password = localStorage.getItem('iaccount_password_ac61be') || '';
  }

  const regFormRef = ref();
  let regForm = reactive({
    username: "",
    password: "",
    password_re: ""
  });
  function doRegister() {
    regFormRef.value.validate((valid) => {
      if(valid) {
        registerReq(regForm.username, regForm.password)
          .then(res => {
            if(res.data.msg === "成功") {
              message.success('注册成功，请登录');
              handleTabChange();
            } else {
              message.warning(res.data.msg);
            }
          })
          .catch(err => {
            message.warning('系统出错，请重试');
            console.warn(err);
          });
      }
    });
  }

  const validateUname = (rule, value, callback) => {
    if(value === '')
      callback(new Error('用户名不能为空！'));
    else if(value.length < 5)
      callback(new Error('用户名需大于5位！'));
    else
      callback();
  };
  const validatePwd = (rule, value, callback) => {
    if(value === '')
      callback(new Error('密码不能为空！'));
    else if(value.length < 8)
      callback(new Error('密码需大于8位！'));
    else
      callback();
  };
  const validateRePwd = (rule, value, callback) => {
    if(value === '')
      callback(new Error('密码不能为空！'));
    else if(value.length < 8)
      callback(new Error('密码需大于8位！'));
    else if(value !== regForm.password)
      callback(new Error('重复密码不符！'));
    else
      callback();
  };
  const rules_log = reactive({
    username: [{ validator: validateUname, trigger: 'blur' }],
    password: [{ validator: validatePwd, trigger: 'blur' }],
  });
  const rules_reg = reactive({
    username: [{ validator: validateUname, trigger: 'blur' }],
    password: [{ validator: validatePwd, trigger: 'blur' }],
    password_re: [{ validator: validateRePwd, trigger: 'blur' }],
  });

  onMounted(() => {
    readRememberInfo();
  });
</script>

<style lang="scss" scoped>
  .cover-image-box{
    width: 100%;
    height: 180px;
    background: url(../assets/cover.jpg) no-repeat;
    background-size: cover;
    position: relative;
    border-bottom-left-radius: 16px;
    border-bottom-right-radius: 16px;
    span{
      font-size: 40px;
      font-weight: 700;
      color: white;
      position: absolute;
      left: 15px;
      bottom: 5px;
    }
  }
  .form-container{
    width: 75%;
    margin: auto;
    margin-top: 30px;
    position: relative;
    .form-box{
      width: 100%;
      position: absolute;
      top: 0;
      left: 0;
    }
    .affair-button{
      width: 85%;
      margin: auto;
      margin-top: 5px;
    }
    .version{
      width: fit-content;
      margin: auto;
      margin-top: 20px;
      font-size: 13px;
      color: $theme-shadow;
    }
    .switch-tag{
      font-size: 15px;
      margin: auto;
      color: $theme-main;
      cursor: pointer;
    }
    .switch-tag:hover{
      color: $theme-main-light;
    }
  }
  .login-enter-active, .reg-enter-active{
    animation: switchtab 1s;
  }
  .login-leave-active, .reg-leave-active{
    animation: switchtab 1s reverse;
  }
  @keyframes switchtab {
    from {
      opacity: 0;
      transform: scale(0.5);
    }
    to {
      opacity: 1;
      transform: scale(1);
    }
  }
</style>